package com.tengju.bff.interfaces.shared;


import com.tengju.user.domain.shared.ResultCodeEnum;

import java.io.Serializable;


public class ApiResponse<T> implements Serializable {

    private static final long serialVersionUID = 1L;
    
    private static final int HEALTH_CHECK_CODE = 0;
    
    private static final String HEALTH_CHECK_MSG = "success";

    public ApiResponse() {

    }

    /**
     * 结果响应码，默认是0-成功
     */
    private int code = 0;
    /**
     * 结果文字描述信息，默认是“成功”
     */
    private String msg = "success";
    /**
     * 返回的数据，调用失败时为Null
     */
    private T data;

    /**
     * 返回一个不需要data属性的调用成功结果
     *
     * @return
     */
    public static <T> ApiResponse<T> newSuccess() {
        ApiResponse<T> result = new ApiResponse<>();
        return result;
    }

    /**
     * 返回一个携带data属性的调用成功结果
     *
     * @return
     */
    public static <T> ApiResponse<T> newSuccess(T data) {
        ApiResponse<T> result = new ApiResponse<>();
        result.setData(data);
        return result;
    }
    
    /**
     * 返回健康检查成功结果
     *
     * @return
     */
    public static <T> ApiResponse<T> newHealthCheckSuccess(T data) {
        ApiResponse<T> result = new ApiResponse<>();
        result.setData(data);
        result.setCode(HEALTH_CHECK_CODE);
        result.setMsg(HEALTH_CHECK_MSG);
        return result;
    }

    /**
     * 返回一个调用失败，自定义errCode和msg的调用结果
     *
     * @return
     */
    public static <T> ApiResponse<T> newFailure(int errCode, String msg) {
        ApiResponse<T> result = new ApiResponse<>();
        result.setCode(errCode != 0 ? errCode : -1);
        result.setMsg(msg);
        return result;
    }

    public static <T> ApiResponse<T> newFailure(ResultCodeEnum resultCodeEnum) {
        if (null == resultCodeEnum) {
            resultCodeEnum = ResultCodeEnum.SYS_EXCEPTION;
        }
        ApiResponse<T> result = new ApiResponse<>();
        result.setCode(resultCodeEnum.getCode() != 0 ? resultCodeEnum.getCode() : -1);
        result.setMsg(resultCodeEnum.getMsg());
        return result;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isSuccess(){
        return  code == 0;
    }

}
